import router from './router'
import store from './store'
import { asyncRouter } from './router/index'

import { getToken } from '@/utils/auth' // get token from cookie
// import NProgress from 'nprogress' // progress bar

function flattenTree (tree, result = [], parentId = null) {
  tree.forEach(node => {
    // 克隆节点，避免直接修改原始对象
    const newNode = { ...node, parentId }
    // 删除子节点，因为我们要扁平化结构
    delete newNode.menuList
    // 将节点添加到结果数组中
    result.push(newNode)
    // 如果存在子节点，递归调用自身
    if (node.menuList && node.menuList.length) {
      flattenTree(node.menuList, result, node.id)
    }
  })
  return result
}
function inWhiteList (toPath) {
  const whiteList = ['/login', '/404']
  const path = whiteList.find(value => {
    // 使用正则匹配
    const reg = new RegExp('^' + value)
    return reg.test(toPath)
  })
  return !!path
}

router.beforeEach(async (to, from, next) => {
  const hasToken = getToken()
  const hasRotes = store.getters.routes
  if (inWhiteList(to.path)) {
    next()
  } else {
    if (hasToken) {
      // console.log(11);
      if (hasRotes.length > 2) {
        // console.log(111);
        next()
      } else {
        // console.log(112);
        const id = localStorage.getItem('role_id')
        if (!id) {
          next('/login')
          return
        }
        const { data } = await store.dispatch('user/getMenuList', { id })
        // console.log(data)
        const flatTree = flattenTree(data)

        const arr1 = flatTree.filter(item => item.menuType !== 'F')
        const arr2 = arr1.map(item => item.path)

        const btnArr = flatTree.filter(item => item.menuType === 'F')
        const arr3 = btnArr.map(item => item.path)

        store.commit('user/storeBtnList', arr3)

        const actionRouter = asyncRouter.filter(item =>
          arr2.includes(item.name)
        )

        store.commit('user/updateRoutes', actionRouter)
        actionRouter.forEach(route => {
          router.addRoute(route)
        })
        next({ ...to, replace: true })
      }
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  // finish progress bar
})
